import { useEffect, useState, forwardRef, useRef } from 'react';
import { App } from 'antd';
import loadable from '@loadable/component';

import { isRegMobile, customSetTimeout } from '@/utils';
import { sendSms } from '@/service/base';

import styles from './index.module.scss';

export default forwardRef((props, ref) => {
    const timeLimit = 60;
    const initState = () => ({
        submitting: false,
        success: false,
        time: timeLimit,
        sending: false,
        counting: false,
    });
    const [state, setState] = useState(initState);
    const stateRef = useRef({});
    const loopHandler = useRef(null);
    const propPhone = useRef('');
    const { message } = App.useApp();

    // 发送验证码
    const sendCaptcha = (captcha={}) => {
        message.destroy();

        const { phone, type='register' } = propPhone.current || {};
        const { sending, counting } = stateRef.current || {};

        if(!phone || sending || counting) return;

        setState(o => ({...o, sending: true}));
        sendSms({phone, state: type, ...captcha}).then(response => {
            setState(o => ({...o, sending: false}));

            if(OK_CODE === response?.code) {
                setState(o => ({...o, counting: true}));
                message.success(`验证码已发送，注意查收`);

                let timeLoopNumber = timeLimit;

                loopHandler.current = customSetTimeout((v) => {
                    if(timeLoopNumber <= 0) {
                        setState(o => ({...o, time: timeLimit, counting: false}));
                        loopHandler.current();
                    }else{
                        timeLoopNumber--;
                        setState(o => ({...o, time: timeLoopNumber}));
                    }
                }, 1000);
            }else{
                setState(o => ({...o, counting: false}));
                message.warning(response?.msg);
            }
        }).catch(e => {
            setState(o => ({...o, sending: false, counting: false}));
            message.error(e?.message || e?.msg);
        });
    }
    // 图形验证么
    const imageVerify = () => {
        // 初始化验证码  弹出式
        $('#verify-container').empty(); // 先清空再初始化
        $('#verify-container').slideVerify({
            baseUrl: `${API_PREFIX || ''}`,  //服务器请求地址, 默认地址为安吉服务器;
            mode:'pop',     //展示模式
            containerId:'verify',//pop模式 必填 被点击之后出现行为验证码的元素id
            imgSize : {       //图片的大小对象,有默认值{ width: '310px',height: '155px'},可省略
                width: '350px',
                height: '160px',
            },
            barSize:{          //下方滑块的大小对象,有默认值{ width: '310px',height: '50px'},可省略
                width: '350px',
                height: '32px',
            },
            beforeCheck:function(){  //检验参数合法性的函数  mode ="pop"有效
                const {phone} = propPhone.current || {};
                if(!phone) {
                    message.warning(`手机号码不能为空`);
                    return false;
                }
                return !(stateRef.current.counting || stateRef.current.sending);
            },
            ready : function() {
                console.log(`ready`);
            },  //加载完毕的回调
            success : function(params) { //成功的回调
                sendCaptcha(params);
                // params为返回的二次验证参数 需要在接下来的实现逻辑回传服务器
                // 例如: login($.extend({}, params))
            },
            error : function(e) { //失败的回调
                console.log(`error`, e.message);
            }
        });
    };

    useEffect(() => {
        stateRef.current = state;
    }, [state]);
    useEffect(() => {
        propPhone.current = props;
    }, [props]);
    useEffect(() => {
        window.__VERIFY_READY = true;
        imageVerify();

        return () => {
            // 取消计时轮询
            loopHandler.current && loopHandler.current();
            $('#verify-container').empty();
            window.__VERIFY_READY = false;
        }
    }, []);

    return (
        <>
            <div className={styles['container']} id="verify">
                {state.sending ? '发送中...' : ''}
                {state.counting ? `${state.time}s 后重试` : ''}
                {!state.sending && !state.counting ? '获取验证码' : ''}
            </div>
        </>
    )
});
